package randomthoughts.dp;

/** leetCode 483
 * @author tongchen
 * @create 2023-05-09 21:01
 */
public class RemovingTwoStrings {
    //动规五部曲：dp[i][j]:以i-1 和j-1为结尾的字符串相等需要移动的步数
    //递推公式： if(i==j)dp[i][j]=dp[i-1][j-1]
    //  (i!=j)dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+2)
    //初始化：dp[i][0]=i; dp[0][j]=j
    //遍历顺序：从前往后遍历
    public int minDistance(String word1, String word2) {
        //创建dp数组
        int[][]dp=new int[word1.length()+1][word2.length()+1];
        //初始化
        for(int i=0;i<=word1.length();++i){
            dp[i][0]=i;
        }
        for(int j=0;j<=word2.length();++j){
            dp[0][j]=j;
        }
        //进行遍历
        for(int i=1;i<=word1.length();++i){
            for(int j=1;j<=word2.length();++j){
                if(word1.charAt(i-1)==word2.charAt(j-1)){
                    dp[i][j]=dp[i-1][j-1];
                }else{
                    dp[i][j]=Math.min(dp[i][j-1]+1,Math.min(dp[i-1][j]+1,dp[i-1][j-1]+2));
                }
            }
        }
        return dp[word1.length()][word2.length()];
    }
}
